package com.sleep.psy.external_server.business.evaluation.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sleep.psy.external_server.business.evaluation.entity.EvaluationRecord;
import com.sleep.psy.external_server.business.evaluation.entity.EvaluationReport;
import com.sleep.psy.external_server.business.evaluation.entity.dto.ReportDto;
import com.sleep.psy.external_server.business.evaluation.entity.dto.Res;
import com.sleep.psy.external_server.business.evaluation.entity.dto.TrainingReport;
import com.sleep.psy.external_server.business.evaluation.mapper.EvaluationRecordMapper;
import com.sleep.psy.external_server.business.evaluation.mapper.EvaluationReportMapper;
import com.sleep.psy.external_server.business.evaluation.service.EvaluationReportService;
import com.sleep.psy.external_server.business.main.entity.MainUser;
import com.sleep.psy.external_server.business.main.service.MainUserService;
import com.sleep.psy.external_server.business.psy.entity.PsyContent;
import com.sleep.psy.external_server.business.psy.entity.PsyScore;
import com.sleep.psy.external_server.business.psy.entity.PsySection;
import com.sleep.psy.external_server.business.psy.mapper.PsyContentMapper;
import com.sleep.psy.external_server.business.psy.mapper.PsyScoreMapper;
import com.sleep.psy.external_server.business.psy.mapper.PsySectionMapper;
import com.sleep.psy.external_server.business.psy.service.PsyScoreService;
import com.sleep.psy.external_server.business.resourse.entity.ResourseScale;
import com.sleep.psy.external_server.business.resourse.mapper.ResourseScaleMapper;
import com.sleep.psy.external_server.constants.CommonEnum;
import com.sleep.psy.external_server.constants.MySqlConstant;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sleep.psy.external_server.property.SleepProperties;
import com.sleep.psy.external_server.result.Result;
import com.sleep.psy.external_server.result.ResultEnum;
import com.sleep.psy.external_server.result.ResultUtil;
import com.sleep.psy.external_server.utils.DateUtils;
import com.sleep.psy.external_server.utils.SleepSuggestionGeneratorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 测评报告 服务实现类
 * </p>
 *
 * @author wenliguo
 * @since 2025-08-12
 */
@Service
public class EvaluationReportServiceImpl extends ServiceImpl<EvaluationReportMapper, EvaluationReport> implements EvaluationReportService {

    protected Logger logger = LoggerFactory.getLogger(EvaluationReportService.class);

    @Autowired
    private EvaluationReportMapper evaluationReportMapper;

    @Autowired
    private EvaluationRecordMapper evaluationRecordMapper;

    @Autowired
    private MainUserService mainUserService;

    @Autowired
    private PsyContentMapper psyContentMapper;

    @Autowired
    private PsyScoreMapper psyScoreMapper;

    @Autowired
    private PsySectionMapper psySectionMapper;

    @Autowired
    private PsyScoreService psyScoreService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ResourseScaleMapper scaleMapper;

    @Autowired
    private SleepProperties sleepProperties;

    /**
     * 获取匹兹堡简易报告
     * @author wenliguo
     * @date 2025/6/6 10:31
     * @param reportId 报告id
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    public Result simpleSleepReport(Long reportId) {
        logger.info("获取匹兹堡简易报告");

        EvaluationReport report = evaluationReportMapper.selectById(reportId);
        if (null == report) {
            logger.info("通过reportId:{},未查到报告", reportId);
            return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
        }

        String simpleReport = report.getSimpleReport();
        if (null == simpleReport) {
            logger.info("首次生成");
            EvaluationRecord record = evaluationRecordMapper.selectById(report.getRecordId());
            if (null == record) {
                logger.info("通过recordId:{},未查到测评记录", report.getRecordId());
                return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
            }

            Long userId = record.getUserId();
            MainUser user = mainUserService.selectById(userId);
            if (null == user) {
                return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
            }
            return ResultUtil.success(generateSleepSimpleReport(user,record,reportId));
        }
        return ResultUtil.success(simpleReport);
    }

    /**
     * 获取通用报告
     * @author wenliguo
     * @date 2025/7/23 14:29
     * @param reportId 报告id
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    public Result generalReport(Long reportId) {
        logger.info("获取通用报告");

        EvaluationReport report = evaluationReportMapper.selectById(reportId);

        if (null == report) {
            logger.info("通过reportId:{},未查到报告", reportId);
            return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
        }

        String professionalReport = report.getProfessionalReport();
        if(null == professionalReport) {
            logger.info("首次生成");
            EvaluationRecord record = evaluationRecordMapper.selectById(report.getRecordId());
            if (null == record) {
                logger.info("通过recordId:{},未查到测评记录", report.getRecordId());
                return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
            }

            Long userId = record.getUserId();
            MainUser user = mainUserService.selectById(userId);
            if (null == user) {
                return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
            }

            return ResultUtil.success(generalReport(user,record,reportId));
        }

        return ResultUtil.success(professionalReport);

    }

    /**
     * 获取匹兹堡专业报告
     * @author wenliguo
     * @date 2025/6/6 10:58
     * @param reportId 报告id
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    public Result professionalSleepReport(Long reportId) {
        logger.info("获取匹兹堡专业报告");

        EvaluationReport report = evaluationReportMapper.selectById(reportId);
        if (null == report) {
            logger.info("通过reportId:{},未查到报告", reportId);
            return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
        }

        String professionalReport = report.getProfessionalReport();
        if (null == professionalReport) {
            logger.info("首次生成");
            EvaluationRecord record = evaluationRecordMapper.selectById(report.getRecordId());
            if (null == record) {
                logger.info("通过recordId:{},未查到测评记录", report.getRecordId());
                return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
            }

            Long userId = record.getUserId();
            MainUser user = mainUserService.selectById(userId);
            if (null == user) {
                return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
            }
            return ResultUtil.success(generateSleepProfessionalReport(user,record,reportId));
        }
        return ResultUtil.success(professionalReport);
    }

    /**
     * 获取睡眠问卷简易报告
     * @author wenliguo
     * @date 2025/6/6 15:27
     * @param reportId 报告id
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    public Result simpleSleepQuestionReport(Long reportId) {
        logger.info("获取睡眠问卷简易报告");

        EvaluationReport report = evaluationReportMapper.selectById(reportId);
        if (null == report) {
            logger.info("通过reportId:{},未查到报告", reportId);
            return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
        }

        String simpleReport = report.getSimpleReport();
        if (null == simpleReport) {
            logger.info("首次生成");
            EvaluationRecord record = evaluationRecordMapper.selectById(report.getRecordId());
            if (null == record) {
                logger.info("通过recordId:{},未查到测评记录", report.getRecordId());
                return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
            }

            Long userId = record.getUserId();
            MainUser user = mainUserService.selectById(userId);
            if (null == user) {
                return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
            }
            return ResultUtil.success(generateSleepQuestionSimpleReport(user,record,reportId));
        }
        return ResultUtil.success(simpleReport);
    }

    /**
     * 通过测评记录id获取有效测评报告
     * @author wenliguo
     * @date 2025/6/9 11:35
     * @param recordId 测评记录id
     * @return com.sleep.psy.main_server.business2.evaluation.entity.EvaluationReport
     */
    @Override
    public EvaluationReport selectReport(Long recordId) {
        QueryWrapper<EvaluationReport> wrapper = new QueryWrapper<>();
        wrapper.eq("record_id", recordId)
                .eq("status", MySqlConstant.STATUS_1);
        return evaluationReportMapper.selectOne(wrapper);
    }

    /**
     * 失眠严重指数量表简易报告
     * @author wenliguo
     * @date 2025/7/10 09:08
     * @param reportId 报告id
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    public Result simpleIsiReport(Long reportId) {
        logger.info("失眠严重指数量表简易报告");

        EvaluationReport report = evaluationReportMapper.selectById(reportId);
        if (null == report) {
            logger.info("通过reportId:{},未查到报告", reportId);
            return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
        }

        String simpleReport = report.getSimpleReport();
        if (null == simpleReport) {
            logger.info("首次生成");
            EvaluationRecord record = evaluationRecordMapper.selectById(report.getRecordId());
            if (null == record) {
                logger.info("通过recordId:{},未查到测评记录", report.getRecordId());
                return ResultUtil.error(ResultEnum.RESOURCE_NOT_FOUND);
            }

            Long userId = record.getUserId();
            MainUser user = mainUserService.selectById(userId);
            if (null == user) {
                return ResultUtil.error(ResultEnum.USER_NOT_EXIST);
            }
            return ResultUtil.success(generateIsiSimpleReport(user,record,reportId));
        }
        return ResultUtil.success(simpleReport);
    }

    /**
     * 生成通用报告
     * @author wenliguo
     * @date 2025/7/23 14:48
     * @param user 用户id
     * @param record 测评记录
     * @param reportId 报告id
     * @return java.lang.String
     */
    private String generalReport(MainUser user, EvaluationRecord record, Long reportId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", user);//用户信息
        map.put("recordInfo", record);//报告记录

        Integer scaleId = record.getScaleId();

        QueryWrapper<PsySection> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("report_id", reportId)
                .orderByAsc("sort_index");
        List<PsySection> sections = psySectionMapper.selectList(sectionQueryWrapper);
        if (!sections.isEmpty()) {
            map.put("sectionList", sections);//作答记录
            StringBuilder answer = new StringBuilder();
            for (PsySection section : sections) {
                double value = section.getValue();
                int intValue = (int) value;
                answer.append(intValue).append(",");
            }

            ResourseScale scale = scaleMapper.selectById(scaleId);

            MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
            multiValueMap.add("title",scale.getScaleName());
            multiValueMap.add("answer",answer);
            ReportDto reportDto = requestPhp(multiValueMap);
            if (null != reportDto.getData()) {
                Res dtoData = reportDto.getData();
                map.put("title", dtoData.getInfo().getTitle());
                map.put("msg", dtoData.getMsg());
                map.put("result", dtoData.getResultArr());
            }
        }

        EvaluationReport evaluationReport = new EvaluationReport();
        evaluationReport.setId(reportId);
        String jsonString = JSON.toJSONString(map);
        evaluationReport.setProfessionalReport(jsonString);
        evaluationReportMapper.updateById(evaluationReport);
        return jsonString;
    }

    /**
     * 生成睡眠问卷简易报告
     * @author wenliguo
     * @date 2025/6/6 15:26
     * @param user 用户信息
     * @param record 测评记录
     * @param reportId 报告id
     * @return java.lang.String
     */
    private String generateSleepQuestionSimpleReport(MainUser user, EvaluationRecord record, Long reportId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", user);//用户信息
        map.put("recordInfo", record);//报告记录
        QueryWrapper<PsyScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_id", reportId);
        List<PsyScore> scores = psyScoreMapper.selectList(queryWrapper);
        if (!scores.isEmpty()) {
            map.put("psyScoreTotal",scores.get(0).getOriginScore());
        }

        String jsonString = JSON.toJSONString(map);
        EvaluationReport evaluationReport = new EvaluationReport();
        evaluationReport.setId(reportId);
        evaluationReport.setSimpleReport(jsonString);
        evaluationReportMapper.updateById(evaluationReport);
        return jsonString;
    }


    /**
     * 生成专业报告
     * @author wenliguo
     * @date 2025/6/6 10:58
     * @param user 用户
     * @param record 测评记录
     * @param reportId 报告id
     * @return java.lang.String
     */
    private String generateSleepProfessionalReport(MainUser user, EvaluationRecord record, Long reportId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", user);//用户信息
        map.put("recordInfo", record);//报告记录

        QueryWrapper<PsyScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_id", reportId);
        List<PsyScore> scores = psyScoreMapper.selectList(queryWrapper);
        if (!scores.isEmpty()) {
            map.put("psyScoreList", scores);//报告因子
        }

        QueryWrapper<PsySection> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("report_id", reportId);
        List<PsySection> sections = psySectionMapper.selectList(sectionQueryWrapper);
        if (!sections.isEmpty()) {
            map.put("sectionList", sections);//作答记录
        }

        QueryWrapper<PsyContent> wrapper = new QueryWrapper<>();
        wrapper.eq("class_name", CommonEnum.InventoryEnum.PSQI.getCode())
                .eq("score_type", CommonEnum.ScoreTypeEnum.PROFESSIONAL.getCode());
        List<PsyContent> contents = psyContentMapper.selectList(wrapper);
        EvaluationReport evaluationReport = new EvaluationReport();
        evaluationReport.setId(reportId);
        if (!contents.isEmpty()) {
            map.put("part1",
                    contents.stream()
                            .filter(PsyContent -> PsyContent.getScoreMeata().equals(CommonEnum.ScoreMeataEnum.PART_1.getCode()))
                            .collect(Collectors.toList()).get(0).getShowInfo());


            // 1.因子判断--总分 判断总分是否大于8分
            PsyScore psyScore = scores.stream().filter(PsyScore -> PsyScore.getClassName().equals("psqi.TOTAL"))
                    .collect(Collectors.toList()).get(0);

            String part2_gt8 = contents.stream()
                    .filter(PsyContent -> PsyContent.getScoreMeata().equals(CommonEnum.ScoreMeataEnum.PART_2.getCode())
                            && PsyContent.getScoreMeataConditions().equals("gt8"))
                    .collect(Collectors.toList()).get(0).getShowInfo();

            String part2_le8 = contents.stream()
                    .filter(PsyContent -> PsyContent.getScoreMeata().equals(CommonEnum.ScoreMeataEnum.PART_2.getCode())
                            && PsyContent.getScoreMeataConditions().equals("le8"))
                    .collect(Collectors.toList()).get(0).getShowInfo();

            map.put("part2", part2_le8);
            if (psyScore.getOriginScore() > 8) {
                map.put("part2", part2_gt8);
            }
            map.put("psyScoreTotal", psyScore.getOriginScore());//总分
        }

        String jsonString = JSON.toJSONString(map);
        evaluationReport.setProfessionalReport(jsonString);
        evaluationReportMapper.updateById(evaluationReport);
        return jsonString;

    }

    /**
     * 生成简易的匹兹堡报告
     * @author wenliguo
     * @date 2025/6/6 10:27
     * @param user 用户
     * @param record 测评记录
     * @param reportId 报告id
     * @return com.sleep.psy.main_server.business2.evaluation.entity.EvaluationReport
     */
    private String generateSleepSimpleReport(MainUser user, EvaluationRecord record, Long reportId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", user);//用户信息
        map.put("reportInfo",record);//测评记录

        QueryWrapper<PsyContent> wrapper = new QueryWrapper<>();
        wrapper.eq("class_name", CommonEnum.InventoryEnum.PSQI.getCode())
                .eq("score_type", CommonEnum.ScoreTypeEnum.SIMPLE.getCode());
        List<PsyContent> contents = psyContentMapper.selectList(wrapper);

        EvaluationReport evaluationReport = new EvaluationReport();
        evaluationReport.setId(reportId);
        if (!contents.isEmpty()) {
            QueryWrapper<PsyScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("report_id", reportId);
            List<PsyScore> scores = psyScoreMapper.selectList(queryWrapper);

            // 1.因子判断--总分 判断总分是否大于8分
            PsyScore psyScore = scores.stream().filter(PsyScore -> PsyScore.getClassName().equals("psqi.TOTAL"))
                    .collect(Collectors.toList()).get(0);

            String part2_gt8 = contents.stream()
                    .filter(PsyContent -> PsyContent.getScoreMeata().equals(CommonEnum.ScoreMeataEnum.PART_1.getCode())
                            && PsyContent.getScoreMeataConditions().equals("gt8"))
                    .collect(Collectors.toList()).get(0).getShowInfo();

            String part2_le8 = contents.stream()
                    .filter(PsyContent -> PsyContent.getScoreMeata().equals(CommonEnum.ScoreMeataEnum.PART_1.getCode())
                            && PsyContent.getScoreMeataConditions().equals("le8"))
                    .collect(Collectors.toList()).get(0).getShowInfo();

            map.put("part2", part2_le8);
            if (psyScore.getOriginScore() > 8) {
                map.put("part2", part2_gt8);
            }

            map.put("psyScoreTotal", psyScore.getOriginScore());//总分
        }

        String jsonString = JSON.toJSONString(map);
        evaluationReport.setSimpleReport(jsonString);
        evaluationReportMapper.updateById(evaluationReport);
        return jsonString;

    }

    /**
     * 生成isi简易报告
     * @author wenliguo
     * @date 2025/7/10 08:58
     * @param user 用户
     * @param record 测评记录
     * @param reportId 测评报告id
     * @return java.lang.String
     */
    private String generateIsiSimpleReport(MainUser user, EvaluationRecord record, Long reportId) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", user);//用户信息
        map.put("recordInfo", record);//报告记录
        map.put("psyScoreTotal", 0);//总分
        QueryWrapper<PsyScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_id", reportId);
        List<PsyScore> scores = psyScoreMapper.selectList(queryWrapper);
        if (!scores.isEmpty()) {
            map.put("psyScoreList", scores);//报告因子
        }

        Double totalScore = 0D;
        PsyScore score = psyScoreService.selectScoreByReportIdAndClassName(reportId, "isi.TOTAL");
        if (null != score) {
            totalScore = score.getOriginScore();
            map.put("psyScoreTotal", score.getOriginScore());//总分
        }

        QueryWrapper<PsySection> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("report_id", reportId);
        List<PsySection> sections = psySectionMapper.selectList(sectionQueryWrapper);
        if (!sections.isEmpty()) {
            map.put("sectionList", sections);//作答记录
        }

        QueryWrapper<PsyContent> wrapper = new QueryWrapper<>();
        wrapper.eq("class_name", CommonEnum.InventoryEnum.ISI.getCode())
                .eq("score_type", CommonEnum.ScoreTypeEnum.SIMPLE.getCode());
        List<PsyContent> contents = psyContentMapper.selectList(wrapper);
        String showInfo = null;
        if (!contents.isEmpty()) {
            for (PsyContent content : contents) {
                String conditions = content.getScoreMeataConditions();
                if (null != conditions) {
                    String[] split = conditions.split("-");
                    String minNum = split[0];
                    String maxNum = split[1];
                    if (totalScore >= Double.parseDouble(minNum) && totalScore <= Double.parseDouble(maxNum)) {
                        showInfo = content.getShowInfo();
                        break;
                    }

                }
            }
        }
        map.put("part1", showInfo);
        EvaluationReport evaluationReport = new EvaluationReport();
        evaluationReport.setId(reportId);
        String jsonString = JSON.toJSONString(map);
        evaluationReport.setProfessionalReport(jsonString);
        evaluationReportMapper.updateById(evaluationReport);
        return jsonString;
    }

    /**
     * 请求php获取报告
     * @author wenliguo
     * @date 2025/7/25 10:15
     * @param map 请求参数
     * @return com.sleep.psy.main_server.business2.evaluation.entity.dto.ReportDto
     */
    @Override
    public ReportDto requestPhp(MultiValueMap<String, Object> map) {

        try {
            logger.info("请求php获取报告参数:{}", JSON.toJSONString(map));
            String url = sleepProperties.getGetPhpReportUrl();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
            ResponseEntity<ReportDto> response = restTemplate.postForEntity(url, param, ReportDto.class);
            logger.info("请求php获取报告返回内容:{}", JSON.toJSONString(response));

            ReportDto res = null;
            if (response.getStatusCode().is2xxSuccessful()) {
                res = response.getBody();
            }
            return res;

        } catch (Exception e) {
            logger.error("请求php获取报错出错", e);
            return null;
        }

    }

    /**
     * 通过用户id获取全部报告
     * @author wenliguo
     * @date 2025/8/18 09:21
     * @param userId 用户id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result selectReportByUserId(Long userId) {
        return ResultUtil.success(evaluationReportMapper.selectReportByUserId(userId));
    }

    /**
     * 通过报告id获取报告
     * @author wenliguo
     * @date 2025/8/18 09:44
     * @param reportId 报告id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result selectReportById(Long reportId) {
        QueryWrapper<EvaluationReport> wrapper = new QueryWrapper<>();
        wrapper.eq("id", reportId)
                .eq("status", MySqlConstant.STATUS_1);
        return ResultUtil.success(evaluationReportMapper.selectOne(wrapper));
    }

    /**
     * 生成失眠问卷的报告
     * @author wenliguo
     * @date 2025/9/1 14:32
     * @param user 用户信息
     * @param record 测评信息
     * @param reportId 报告id
     */
    @Override
    public void generateSleeplessReport(MainUser user, EvaluationRecord record, Long reportId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo", user);//用户信息
        map.put("recordInfo", record);//报告记录
        QueryWrapper<PsySection> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.eq("report_id", reportId);
        List<PsySection> sections = psySectionMapper.selectList(sectionQueryWrapper);
        if (!sections.isEmpty()) {
            map.put("sectionList", sections);//作答记录

            //上床时间  入睡时间 醒来时间（最后一次） 起床时间  中途清醒时间总和  中午午睡时间总和
            String t1 = null, t2 = null, t3 = null, t4 = null, t5 = null, t6 = null;
            for (PsySection section : sections) {
                String template = section.getTemplate();
                String text = section.getText();
                if (template.contains("上床时间（有失眠症状之后）")) {
                    t1 = text;
                }
                if (template.contains("入睡时间（有失眠症状之后）")) {
                    t2 = text;
                }
                if (template.contains("醒来时间（有失眠症状之后）")) {
                    t3 = text;
                }
                if (template.contains("起床时间（有失眠症状之后）")) {
                    t4 = text;
                }
                if (template.contains("中午午睡时间总和（有失眠症状之后）（小时:分钟）")) {
                    t5 = text;
                }
                if (template.contains("中途清醒时间总和（有失眠症状之后）（小时:分钟）")) {
                    t6 = text;
                }
            }

            List<String> list = SleepSuggestionGeneratorUtils.generateSleepTips(LocalTime.parse(t1), LocalTime.parse(t2), LocalTime.parse(t3), LocalTime.parse(t4), convert(t5), convert(t6));

            map.put("report", JSON.toJSONString(list));
            EvaluationReport evaluationReport = new EvaluationReport();
            evaluationReport.setSleepAdvise(JSON.toJSONString(list));
            evaluationReport.setId(reportId);
            String jsonString = JSON.toJSONString(map);
            evaluationReport.setProfessionalReport(jsonString);
            evaluationReportMapper.updateById(evaluationReport);
        }
    }

    /**
     * 转换
     * @author wenliguo
     * @date 2025/9/2 11:45
     * @param hhmm 时间格式
     * @return java.time.Duration
    */
    public  Duration convert(String hhmm) {
        // 检查输入是否为空
        if (hhmm == null || hhmm.trim().isEmpty()) {
            throw new IllegalArgumentException("输入不能为空");
        }

        // 分割小时和分钟部分
        String[] parts = hhmm.split(":");
        if (parts.length != 2) {
            throw new IllegalArgumentException("格式错误，必须为HH:mm（如01:20）");
        }

        try {
            // 解析小时和分钟
            int hours = Integer.parseInt(parts[0].trim());
            int minutes = Integer.parseInt(parts[1].trim());

            // 验证分钟范围
            if (minutes < 0 || minutes > 59) {
                throw new IllegalArgumentException("分钟必须在0-59之间");
            }

            // 构建并返回Duration
            return Duration.ofHours(hours).plusMinutes(minutes);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("小时或分钟必须是数字", e);
        }
    }

    /**
     * 通过用户id查询训练报告
     * @author wenliguo
     * @date 2025/9/9 11:46
     * @param userId 用户id
     * @return java.util.List<com.sleep.psy.external_server.business.evaluation.entity.dto.TrainingReport>
     */
    @Override
    public List<TrainingReport> selectTrainingReport(Long userId) {
        ResourseScale scale = scaleMapper.selectSleepEvaluate();
        if (null == scale) {
            return null;
        }

        List<TrainingReport> reports = evaluationReportMapper.selectTrainingReport(userId, scale.getId());
        if (!reports.isEmpty()) {
            for (TrainingReport report : reports) {
                String dateCreated = report.getDateCreated();
                Date date = DateUtils.stringToDate(dateCreated, DateUtils.DATE_TIME_FORMAT);
                report.setDateCreated(DateUtils.dateToString(date, DateUtils.DATE_FORMAT_M_D));
            }
        }
        return reports;
    }
}
